const request = require('../schedule/createXML').request
const sm = require('sitemap')
// 二级导航权重0.7
let secondPriority = ['/cjkj/', '/zjkj/', '/cpa/', '/cta/', '/mat_g/', '/zjjjs/', '/cma/', '/kjsc/']
String.prototype.endWith = function(str) {
  var reg = new RegExp(str + '$')
  return reg.test(this)
}

// 生成xml URL link
function createXmlUrl(links, name, staticLinks = []) {
  let date = new Date(),
    compute_date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(),
    regularLinks = [],
    priority = 0.5,
    requestLinks = []

  if (['sitemap.xml','wap_sitemap.xml'].includes(name)) {
    links.forEach(item => {
      let _path = item.path.includes('/guide') ? item.path + 'Detail' : item.path + '_detail'
      let item_url = _path + (_path.endWith('/') ? '' : '/') + item.id + '.html',
        item_time = item.create_time.split(' ')[0]
      requestLinks.push({
        url: item_url,
        lastmod: item_time,
        priority: 0.5
      })
    })
  }

  if (name === 'sitemap1.xml') {
    links.forEach(({ path, create_time }) => {
      requestLinks.push({
        url: path,
        lastmod: create_time,
        priority: 0.5
      })
    })
  }
  // 拼接处理固定链接
  staticLinks.forEach(item => {
    if (item === '/') {
      priority = 1
    } else if (secondPriority.includes(item)) {
      priority = 0.7
    } else {
      priority = 0.5
    }
    regularLinks.push({
      url: item,
      lastmod: compute_date,
      priority: priority
    })
  })
  return [...requestLinks, ...regularLinks]
}

// 生成XML文件
function createXML(links, name = 'sitemap.xml', staticLinks) {
  let urls = createXmlUrl(links, name, staticLinks)
  //这里因为sitemap插件包，会修改urls数据，导致wap生成的链接有问题
  try {
    wapUrls = JSON.parse(JSON.stringify(urls))
  } catch (e) {}
  const sitemap = sm.createSitemap({
    // js-ignore
    hostname: 'https://www.zlketang.com',
    urls
  })
  return sitemap.toString()
}

async function requestXML(callback) {
  try {
    // 每日的数据参数默认获取7天的数据
    const dayParams = {
      day: 7
    }
    const res = await Promise.all([
      request('/webapi/api/static_link',{type:1}),  // 获取网站死链接和网站地图
      request('/newsapi/web/news_recent', dayParams), // 获取最近七天文章
      request('/newsapi/web/solution_recent', dayParams) // 获取最近七天答疑
    ])
    let textArr = [],
      siteLinks = [],
      dayiLinks = [],
      wapLinks = []

    const adminUrls = res[0]
    const dayNews = res[1].data
    const dayDayi = res[2].data
    if (adminUrls && adminUrls.data && Object.keys(adminUrls.data).length === 4) {
      // 咨询后台配置链接
      siteLinks = adminUrls.data['1']
      // 答疑后台配置链接
      dayiLinks = adminUrls.data['3']
      // wap后台配置链接
      // wapLinks = adminUrls.data['4']
    }
    
    if (Array.isArray(dayNews)) {
      // pc资讯每日数据
      textArr.push(createXML(dayNews, 'sitemap.xml', siteLinks))
      // wap资讯每日数据
      // textArr.push(createXML(dayNews, 'wap_sitemap.xml', wapLinks))
    }
    // 答疑
    if (Array.isArray(dayDayi.list)) {
      // 相比资讯，答疑的数据结构不一样，需要单独处理
      let list = dayDayi.list.map(({ id, end_time }) => {
        return {
          id: id,
          nav_id: '1',
          profession_id: '7',
          path: `/dayi/${id}.html`,
          create_time: end_time
        }
      })
      textArr.push(createXML(list, 'sitemap1.xml', dayiLinks))
    }

    return textArr
  } catch (err) {
    callback && callback({ code: 1, msg: JSON.stringify(err) })
  }
}

module.exports = requestXML
